package com.time.hellotime.views;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.time.hellotime.R;
import com.time.hellotime.app.AddressManager;
import com.time.hellotime.servermodel.BasicBean;
import com.time.hellotime.utils.MobileUtils;
import com.time.hellotime.utils.NetWorkUtils;
import com.time.hellotime.utils.ToastUtils;
import com.time.hellotime.webserver.helper.WebServerManager;
import com.time.hellotime.webserver.listener.ResponseCallback;
import com.time.hellotime.webserver.request.BasicRequest;
import com.time.hellotime.webserver.request.requestsParamters.LoginParameters;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

import java.lang.ref.WeakReference;


/**
 * 手机验证码自定义布局
 * Author: Created by deng on 2016/8/18.
 * E-mail: tx16bing@163.com
 */
public class TelephoneView extends FrameLayout implements
        ResponseCallback<BasicBean> {

    private Context mContext;
    private EditText etTelephone;
    private TextView tvCode;

    private static final int GET_VALIDATION_TIME = 4;
    private static final int GET_VALIDATION_TIME_OUT = 5;

    public TelephoneView(Context context) {
        super(context);
        this.mContext = context;
    }

    public TelephoneView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        View view = LayoutInflater.from(getContext())
                .inflate(R.layout.item_telephone_code, this, false);
        addView(view);
        initView(view);
    }

    private void initView(final View view) {
        etTelephone = (EditText) view.findViewById(R.id.et_telephone);
        tvCode = (TextView) view.findViewById(R.id.tv_obtain_code);

        etTelephone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        etTelephone.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

            }
        });

        tvCode.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!checkForm()) {
                    return;
                }
                requestCode(MobileUtils.getCodeType(mContext.getString(R.string.verify_code_default)));
            }
        });
    }

    private boolean checkForm() {
        boolean formIsValid = true;
        String phone = etTelephone.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            formIsValid = false;
            ToastUtils.showShort(mContext.getString(R.string.please_input_telephone));
//        }else if (!MobileUtils.isMobile(telephone)){
        } else if (phone.length() != 11) {
            // 判断电话号是否小于11位
            formIsValid = false;
            ToastUtils.showShort(mContext.getString(R.string.please_input_legal_telephone));
        }
        return formIsValid;
    }

    public String getCode() {
        return etTelephone.getText().toString().trim();
    }

    public String getAccount() {
        return etTelephone.getText().toString().trim();
    }

    public void setHintText(int hintText) {
        etTelephone.setHint(hintText);
        invalidate();
    }

    private void requestCode(String type) {
        if (NetWorkUtils.isNetAvailable(mContext)) {
            Request request = new BasicRequest(AddressManager.getInstance().getAddress(), RequestMethod.POST);
            LoginParameters parameters = new LoginParameters();
            parameters.setCommand(mContext.getString(R.string.command_sendCode));
            parameters.setTelephone(etTelephone.getText().toString().trim());
            parameters.setUserType(mContext.getString(R.string.user_type_person));
            parameters.setType(type);
            request.add(mContext.getString(R.string.command), parameters.getCommand());
            request.add(mContext.getString(R.string.platform), parameters.getPlatform());
            request.add(mContext.getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(mContext, request, this, 100,
                    true, true, true);
        } else {
            ToastUtils.showShort(mContext.getString(R.string.network_error));
        }
    }

    private MyHandler codeHandler = new MyHandler(this);

    private static class MyHandler extends Handler {

        private final WeakReference<TelephoneView> mView;

        private MyHandler(TelephoneView telephoneView) {
            this.mView = new WeakReference<>(telephoneView);
        }

        @Override
        public void handleMessage(Message msg) {
            TelephoneView mInstance = mView.get();
            if (mInstance == null){
                return;
            }
            mInstance.handleWhat(msg);
            super.handleMessage(msg);
        }

    }
    public void removeCallback(){
        if (null != codeHandler){
            codeHandler.removeCallbacksAndMessages(null);
        }
    }

    private void handleWhat(Message msg) {
        int result = (Integer) msg.obj;
        switch (msg.what) {

            case GET_VALIDATION_TIME_OUT:
                tvCode.setEnabled(true);
                tvCode.setText(R.string.re_obtain_code_str);
                tvCode.setTextColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
                break;

            case GET_VALIDATION_TIME:
                tvCode.setText(new StringBuilder().append(result).append("s"));
                tvCode.setEnabled(false);
                tvCode.setTextColor(ContextCompat.getColor(mContext, R.color.hint_color));
                break;

            default:
                break;
        }
    }

    /**
     * 倒计时
     */
    private void countDown() {
        new Thread(new Runnable() {
            int time = 60;

            @Override
            public void run() {
                for (int i = time; i > 0; i--) {
                    if (i > 0) {
                        try {
                            if (codeHandler != null) {
                                codeHandler.sendMessage(Message.obtain(codeHandler,
                                        GET_VALIDATION_TIME, i));
                                Thread.sleep(1000);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                if (codeHandler != null) {
                    codeHandler.sendMessage(Message.obtain(codeHandler,
                            GET_VALIDATION_TIME_OUT, time));
                }
            }
        }).start();
    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {
        BasicBean basicBean = response.get();
        if (basicBean == null) return;

        if (basicBean.isSuccess()) {
            // 获取验证码成功
            countDown();
            ToastUtils.showShort(mContext.getString(R.string.attention_to_get_code));

        } else if (basicBean.isChangeCodeType()) {
            requestCode(MobileUtils.getCodeType(mContext.getString(R.string.verify_code_change)));
            countDown();
        } else {
            ToastUtils.showShort(basicBean.getMsg());
            countDown();
        }
    }

    @Override
    public void onFailed(int what, Object tag, Exception exception, long networkMillis) {
        if (exception != null) {
            ToastUtils.showShort(exception.getMessage());
            countDown();
        }
    }

}
